package com.palm.vue.integration;

import com.palm.vue.MJsUtil;
import com.palm.vue.VueResourceLoader;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.web.staticfiles.StaticMappings;

import java.net.URL;

/**
 * 源码转换Handler,用于调试时直接转换源码输出。正式运行时一般就直接使用编译的文件了
 */
public abstract class ResourceTransformHandler implements Handler {
    protected abstract String suffix();
    protected abstract String toSuffix();
    protected abstract String contentType();
    protected abstract String transform(String source);
    @Override
    public void handle(Context ctx) throws Throwable {
        String path=ctx.path();
        //找到需要转换的原文件
        URL url = findFile(path);
        if(url==null){
            return;
        }
        String source = VueResourceLoader.loadText(url.openStream());
        ctx.setHandled(true);
        ctx.contentType(contentType());
        //进行转换
        String os= transform(source);
        ctx.output(os);
    }
    protected URL findFile(String path) throws Exception {
        String newPath=path.replaceFirst("\\."+suffix()+"$","."+toSuffix());
        URL url = StaticMappings.find(newPath);
        return url;
    }
}
